﻿using Lamex.Base;
using Lamex.Library;
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mPE.UI
{
    public partial class frmPDT_PN_AL_BatchModeling : frmBaseChild
    {
        string strCurPath, strTmpPath, strCurModule, strResult, strNewFile;
        DataTable data_Release = new DataTable();//保存模型发布数据
        bool flag = false;
        public frmPDT_PN_AL_BatchModeling()
        {
            InitializeComponent();
        }

        private void frmPDT_PN_AL_BatchModeling_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            
            gridControl1.UseEmbeddedNavigator = true;//显示底部数据导航器
            gridControl2.UseEmbeddedNavigator = true;//显示底部数据导航器
            Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\SavePath.ini");
            string strTarget = ini.IniReadValue("PN_AL_BatchModel", "TargetPath");
            string strFile = ini.IniReadValue("PN_AL_BatchModel", "FilePath");
            if (!string.IsNullOrEmpty(strTarget))
            {
                txtTarget.Text = strTarget;
                strCurPath = strTarget;
            }       
            if (!string.IsNullOrEmpty(strFile))
            {
                txtFile.Text = strFile;
            }
         
        }

        private void btnTargerPath_Click(object sender, EventArgs e)
        {
            //FolderBrowserDialog dialog = new FolderBrowserDialog();
            //dialog.ShowNewFolderButton = false;
            //dialog.Description = "请选择目标路径";
            //dialog.SelectedPath = @"\\Tx-fs10.lamex.com\tx-fs1\LAMEX\Parametric\Sample";
            CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            dialog.InitialDirectory = @"\\Tx-fs10.lamex.com\tx-fs1\LAMEX\Parametric";
            dialog.IsFolderPicker = true;
            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                strCurPath = dialog.FileName;
                txtTarget.Text = strCurPath;
                Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\SavePath.ini");
                ini.IniWriteValue("PN_AL_BatchModel", "TargetPath", strCurPath);
            }         
        }

        private void btnFilePath_Click(object sender, EventArgs e)
        {
            //FolderBrowserDialog dialog = new FolderBrowserDialog();
            //dialog.ShowNewFolderButton = false;
            //dialog.Description = "请选择归档路径";
            //dialog.SelectedPath = @"\\Tx-fs10.lamex.com\tx-fs1\LAMEX\Parametric\Sample";
            CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            dialog.InitialDirectory = @"\\Tx-fs10.lamex.com\tx-fs1\LAMEX\Parametric";
            dialog.IsFolderPicker = true;
            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                strResult = dialog.FileName;
                txtFile.Text = strResult;
                Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\SavePath.ini");
                ini.IniWriteValue("PN_AL_BatchModel", "FilePath", strResult);
            }
        }

        private void btnBatchModel_Click(object sender, EventArgs e)
        {
            try
            {
                //选择剪切目标文件夹路径
                if (string.IsNullOrEmpty(txtFile.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("归档路径不存在,请选择归档路径再操作！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                #region //选择模型文件路径
                //FolderBrowserDialog dialog = new FolderBrowserDialog();
                //dialog.ShowNewFolderButton = false;
                //dialog.Description = "请选择模型文件路径，拆分实例保存在同级路径：" + "\r\n" + "再次实例化前请先删除旧文件！";
                //dialog.SelectedPath = strCurPath;      
                //if (dialog.ShowDialog() == DialogResult.OK)
                //{
                CommonOpenFileDialog dialog = new CommonOpenFileDialog();
                dialog.InitialDirectory = txtTarget.Text;
                dialog.IsFolderPicker = true;
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    gridControl1.DataSource = new DataTable();
                    strCurPath = dialog.FileName;
                    strCurModule = strCurPath.Substring(strCurPath.LastIndexOf("\\") + 1, strCurPath.Length - strCurPath.LastIndexOf("\\") - 1);
                    strTmpPath = strCurPath.Substring(0, strCurPath.Length - strCurModule.Length - 1) + "\\Temp";
                    if (Directory.Exists(strTmpPath))//文件夹存在
                    {
                        DirectoryInfo di = new DirectoryInfo(strTmpPath);
                        di.Delete(true);//删除里面所有的文件，包括文件夹和子文件夹
                    }
                    Directory.CreateDirectory(strTmpPath);//创建文件夹
                }
                else
                {
                    return;
                }
                #endregion
                DataTable table = Common.GetTable.GetTable_DWGPARTNO();
                #region //获取处理清单

                //增加按PART_NO排序，避免因多参数图纸（A6FA248A）创建文件夹时报错中断，2020/6/18 Rocky
                string sql = @"select a.*,b.CREO_VALUE_TYPE from 
                        (select p.DRAWING_NO + '_' + p.PARAMETER_NAME as DWG_PAR,p.* from NC_PN_AL_Detail_Part p) a 
                        left join 
                        (select d.DRAWING_NO + '_' + d.PARAMETER_NAME as DWG_PAR,d.CREO_VALUE_TYPE from NC_PN_AL_Detail_Drawing d) b 
                        on b.DWG_PAR=a.DWG_PAR
                        where a.DRAWING_NO='" + strCurModule + @"'
                        order by PART_NO";

                DataTable dt = BaseBuildSql.GetDataTableBySql(sql);

                #endregion

                if (dt.Rows.Count != 0)
                {
                    #region //拆分实例模型
                    string prePART_NO = "", curPART_NO = "", curMODEL_NO = "", strParFile = "";
                    string strParList = "", strCfgList = "";
                    string parName = "", parValue = "";

                    strCfgList = @"mapkey pmd ~ Command `ProCmdModelEraseNotDisp` ;\" + "\r\n";

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        curPART_NO = dt.Rows[i]["PART_NO"].ToString();
                        //插入到新表显示到前台
                        DataRow dr = table.NewRow();
                        dr["图纸编号"] = strCurModule;
                        dr["部件编号"] = curPART_NO;
                        table.Rows.Add(dr);

                        if (curPART_NO != prePART_NO)//不同部件才进行拆分                
                        {
                            if (strParList != "")
                            {
                                File.WriteAllText(strParFile, strParList, Encoding.UTF8);
                                strParList = "";
                            }

                            prePART_NO = curPART_NO;
                            curMODEL_NO = strCurModule + "_" + curPART_NO;
                            var newPath = strTmpPath + "\\" + curMODEL_NO;
                            strParFile = newPath + "\\" + curMODEL_NO + ".txt";

                            strParList = strParList + "PART_NO = " + "\"" + curPART_NO + "\"" + "\r\n";

                            parName = dt.Rows[i]["PARAMETER_NAME"].ToString();
                            parValue = dt.Rows[i]["PARAMETER_VALUE"].ToString();

                            if (dt.Rows[i]["CREO_VALUE_TYPE"].ToString() == "String")
                            {
                                strParList = strParList + parName + " = " + "\"" + parValue + "\"" + "\r\n";
                            }
                            else
                            {
                                strParList = strParList + parName + " = " + parValue + "\r\n";
                            }

                            //复制所有文件
                            Directory.CreateDirectory(newPath);
                            string[] filenames = Directory.GetFileSystemEntries(strCurPath);
                            foreach (string file in filenames)
                            {
                                strNewFile = file.Substring(file.LastIndexOf("\\") + 1, file.Length - file.LastIndexOf("\\") - 1);
                                File.Copy(file, newPath + "\\" + strNewFile);
                            }

                            strCfgList = strCfgList
                            + @"mapkey(continued) ~ Activate `file_erase_nd` `ok_pb`;~ Command `ProCmdSessionChangeDir` ;\" + "\r\n"
                            + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                            + @"mapkey(continued) ~ Update `file_open` `Inputname` \" + "\r\n"
                            + @"mapkey(continued) `" + @newPath.Replace(@"\", @"\\") + @"`;\" + "\r\n"
                            + @"mapkey(continued) ~ Command `ProFileSelPushOpen@context_dlg_open_cmd` ;\" + "\r\n"
                            + @"mapkey(continued) ~ Command `ProCmdModelOpen` ;\" + "\r\n"
                            + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                            + @"mapkey(continued) ~ Update `file_open` `Inputname` `" + strCurModule + @"`;\" + "\r\n"
                            + @"mapkey(continued) ~ Command `ProFileSelPushOpen_Standard@context_dlg_open_cmd` ;\" + "\r\n"
                            + @"mapkey(continued) ~ Close `main_dlg_cur` `appl_casc`;~ Command `ProCmdModelRename` ;\" + "\r\n"
                            + @"mapkey(continued) ~ Update `rename` `InputPanel2` `" + curMODEL_NO + @"`;\" + "\r\n"
                            + @"mapkey(continued) ~ Activate `rename` `OK`;~ Command `ProCmdRegenPart` ;#READ FILE;\" + "\r\n"
                            + @"mapkey(continued) " + strParFile + @";\" + "\r\n";

                            //因增加自动切换当前工作目录快捷指令，所以代码注释掉，2019-12-24
                            //if (i != dt.Rows.Count - 1)
                            //{
                            strCfgList = strCfgList + @"mapkey(continued) ~ Command `ProCmdModelSave` ;~ Command `ProCmdWinCloseGroup`;\" + "\r\n";
                            //}
                            //else
                            //{
                            //strCfgList = strCfgList + @"mapkey(continued) ~ Command `ProCmdModelSave` ;~ Command `ProCmdWinCloseGroup`;" + "\r\n";
                            //}
                        }
                        else
                        {
                            strParList = strParList + dt.Rows[i]["PARAMETER_NAME"].ToString() + " = " + dt.Rows[i]["PARAMETER_VALUE"].ToString() + "\r\n";
                        }
                    }

                    //增加自动切换当前工作目录到D:\快捷指令，2019-12-24
                    strCfgList = strCfgList
                    + @"mapkey(continued) ~ Command `ProCmdSessionChangeDir` ;\" + "\r\n"
                    + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                    + @"mapkey(continued) ~ Activate `file_open` `computer_pb`;\" + "\r\n"
                    + @"mapkey(continued) ~ Select `file_open` `Ph_list.Filelist` 1 `d:`;\" + "\r\n"
                    + @"mapkey(continued) ~ Command `ProFileSelPushOpen@context_dlg_open_cmd`;" + "\r\n"
                    + @"" + "\r\n"
                    + @"" + "\r\n";

                    //最后一个部件参数文件输出
                    File.WriteAllText(strParFile, strParList, Encoding.UTF8);

                    #endregion

                    #region //生成批处理命令配置文件

                    //切换标准配置文件命令输出
                    strCfgList = strCfgList + "\r\n"
                    + @"mapkey cf ~ Select `main_dlg_cur` `appl_casc`;\" + "\r\n"
                    + @"mapkey(continued) ~ Close `main_dlg_cur` `appl_casc`;~ Command `ProCmdRibbonOptionsDlg` ;\" + "\r\n"
                    + @"mapkey(continued) ~ Select `ribbon_options_dialog` `PageSwitcherPageList` 1 `ConfigLayout`;\" + "\r\n"
                    + @"mapkey(continued) ~ Select `ribbon_options_dialog` `ConfigLayout.ImportExportBtn`;\" + "\r\n"
                    + @"mapkey(continued) ~ Close `ribbon_options_dialog` `ConfigLayout.ImportExportBtn`;\" + "\r\n"
                    + @"mapkey(continued) ~ Activate `ribbon_options_dialog` `ConfigLayout.Open`;\" + "\r\n"
                    + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                    + @"mapkey(continued) ~ Activate `main_dlg_cur` `main_dlg_cur`;\" + "\r\n"
                    + @"mapkey(continued) ~ Update `file_open` `Inputname` `Z:\\Sta\\Rocky he\\Config.pro`;\" + "\r\n"
                    + @"mapkey(continued) ~ Command `ProFileSelPushOpen_Standard@context_dlg_open_cmd` ;\" + "\r\n"
                    + @"mapkey(continued) ~ Activate `ribbon_options_dialog` `OkPshBtn`;\" + "\r\n"
                    + @"mapkey(continued) ~ FocusIn `UITools Msg Dialog Future` `no`;\" + "\r\n"
                    + @"mapkey(continued) ~ Activate `UITools Msg Dialog Future` `no`;" + "\r\n";

                    //批量抽取特征数据时不能识别数字版本，所以设置直接保存
                    strCfgList = strCfgList + "\r\n"
                    + @"save_file_iterations no" + "\r\n";

                    File.WriteAllText(@"D:\Config_Temp.pro", strCfgList, Encoding.UTF8);
                    #endregion

                    //剪切目标文件
                    FolderMove(strCurPath, txtFile.Text + @"\" + strCurModule);
                    //显示回前台
                    gridControl1.DataSource = table;
                    DevExpress.XtraEditors.XtraMessageBox.Show("1.本次批量建模图号【" + strCurModule + "】，物料号数量" + table.Rows.Count + "个，生成待刷新实例模型" + table.Rows.Count + "个。" +
                        "\r\n" +
                         "\r\n" +
                        "2.在Creo环境下，输入CT导入临时配置文件，用PMD命令完成实例模型刷新！" +
                         "\r\n" +
                          "\r\n" +
                        "3.实例模型刷新完成后，点击【模型发布】。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("未找到【" + strCurModule + "】部件参数清单，请先维护！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnModelRelease_Click(object sender, EventArgs e)
        {
            flag = false;
            string srcPath = txtTarget.Text + @"\Temp";//源路径
            if (!Directory.Exists(srcPath))
            {
                Directory.CreateDirectory(srcPath);
            }
            string desPath = @"\\Tx-fs10\tx-fs1\LAMEX\Parametric\Module\For_NC";//目标路径
            //string desPath = @"D:\bin\20201112";//目标路径        
            data_Release = Common.GetTable.GetTable_DWGPARTNO();
            gridControl2.DataSource = data_Release;

            //1、判断是否只包含一级子目录，且只包含一个图号（一次只能发布一张图纸），否则提示并退出
            //TO DO
            //2、判断一级目录（图号_部件号）是否已发布，即检查图号是否出现在[NC_PN_AL_Detail_Part]表中,
            //   如果出现，则再检查发布时间是否为空；满足此两个条件，则提示用户是选择重新发布，还是直接退出
            //TO DO
            //3、重新发布前，删除当前图号相关信息，逻辑待定
            //TO DO

            //4、图纸发布（复制）子程序
            if (CopyFoldersWithSubDir(srcPath, desPath))
            {
                gridControl2.DataSource = data_Release;
                DevExpress.XtraEditors.XtraMessageBox.Show("1.模型发布成功,本次模型发布成功数量" + data_Release.Rows.Count + "个。" +
                    "\r\n" +
                     "\r\n" +
                    "2.全部图纸模型发布完毕后，在CERO环境下，点击【批量特征数据】完成铝材特征数据CSV提取。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            //else
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("模型发布失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            //}
        }
        /// <summary>
        /// 拷贝srcPath的文件到desPath下面
        /// </summary>
        /// <param name="srcPath">源路径(@"用户指定")</param>
        /// <param name="desPath">目标路径(@"\\Tx-fs10\tx-fs1\LAMEX\Parametric\Part")</param>
        /// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
        public bool CopyFoldersWithSubDir(string srcPath, string desPath)
        {
            if (!Directory.Exists(desPath))
            {
                Directory.CreateDirectory(desPath);
            }
            #region //拷贝文件夹到desPath下
            try
            {
                string[] partDirs = Directory.GetDirectories(srcPath);//目录
                string[] partFiles = Directory.GetFiles(srcPath);//文件
                if (partFiles.Length > 0)
                {
                    DateTime time = DateTime.Now;
                    DateTime dt_prt = time, dt_txt = time;
                    for (int i = 0; i < partFiles.Length; i++)
                    {
                        //if (Path.GetExtension(partFiles[i]) != ".xlsx")//排除.xlsx文件
                        //{
                        //    File.Copy(srcPath + "\\" + Path.GetFileName(partFiles[i]), desPath + "\\" + Path.GetFileName(partFiles[i]), true);
                        //}
                        //判断prt\txt文件修改时间
                        if (Path.GetExtension(partFiles[i]) == ".prt")
                        {
                            FileInfo fi = new FileInfo(srcPath + "\\" + Path.GetFileName(partFiles[i]));
                            dt_prt = fi.LastWriteTime;
                        }
                        if (Path.GetExtension(partFiles[i]) == ".txt")
                        {
                            FileInfo fi = new FileInfo(srcPath + "\\" + Path.GetFileName(partFiles[i]));
                            dt_txt = fi.LastWriteTime;
                        }
                    }
                    if (DateTime.Compare(dt_prt, dt_txt) <= 0)
                    {
                        if (Directory.Exists(desPath))//文件夹存在
                        {
                            DirectoryInfo di = new DirectoryInfo(desPath);
                            di.Delete(true);//删除里面所有的文件，包括文件夹和子文件夹
                        }
                        DevExpress.XtraEditors.XtraMessageBox.Show("实例模型待刷新,模型发布失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        flag = true;
                        return false;
                    }
                    for (int i = 0; i < partFiles.Length; i++)
                    {
                        if (Path.GetExtension(partFiles[i]) != ".xlsx")//排除.xlsx文件
                        {
                            File.Copy(srcPath + "\\" + Path.GetFileName(partFiles[i]), desPath + "\\" + Path.GetFileName(partFiles[i]), true);
                        }
                    }
                }
                if (partDirs.Length > 0)
                {
                    for (int j = 0; j < partDirs.Length; j++)
                    {
                        Directory.GetDirectories(srcPath + "\\" + Path.GetFileName(partDirs[j]));
                        //递归调用
                        CopyFoldersWithSubDir(srcPath + "\\" + Path.GetFileName(partDirs[j]), desPath + "\\" + Path.GetFileName(partDirs[j]));
                        if (flag == true) return false;//跳出整个递归
                        //把数据插入到发布表    
                        string[] strList = Path.GetFileName(partDirs[j]).Split('_');
                        if (strList.Length >= 2)
                        {
                            DataRow dr = data_Release.NewRow();
                            dr["图纸编号"] = strList[0];
                            dr["部件编号"] = strList[1];
                            data_Release.Rows.Add(dr);
                        }

                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
            #endregion
            return true;
        }
        /// <summary>
        /// 文件夹移动
        /// </summary>
        /// <param name="srcFolderPath"></param>
        /// <param name="destFolderPath"></param>
        public static void FolderMove(string srcFolderPath, string destFolderPath)
        {
            //检查目标目录是否以目标分隔符结束，如果不是则添加之
            if (destFolderPath[destFolderPath.Length - 1] != Path.DirectorySeparatorChar)
                destFolderPath += Path.DirectorySeparatorChar;
            //判断目标目录是否存在，如果不在则创建之
            //判断目标目录是否存在，如果不在则创建之
            if (Directory.Exists(destFolderPath))//文件夹存在
            {
                DirectoryInfo di = new DirectoryInfo(destFolderPath);
                di.Delete(true);//删除里面所有的文件，包括文件夹和子文件夹
            }
            Directory.CreateDirectory(destFolderPath);//创建文件夹

            string[] fileList = Directory.GetFileSystemEntries(srcFolderPath);

            foreach (string file in fileList)
            {
                if (Directory.Exists(file))
                {
                    FolderMove(file, destFolderPath + Path.GetFileName(file));
                    //Directory.Delete(file);
                }
                else
                    File.Move(file, destFolderPath + Path.GetFileName(file));
            }
            Directory.Delete(srcFolderPath);
        }
        private void frmPDT_PN_AL_BatchModeling_Resize(object sender, EventArgs e)
        {
            groupControl1.Width = this.panelControl2.Width / 2;
            groupControl2.Width = this.panelControl2.Width / 2;
        }
    }
}
